﻿using System;
using System.Web;
using System.Web.Configuration;
using System.Web.Routing;
using Castle.Core.Logging;
using VideoSeller.Core.Configuration;

namespace VideoSeller.Core.Web.Modules
{
    public class HttpErrorModule : IHttpModule
    {
        private static readonly object LockObject = new object();

        public void Init(HttpApplication context)
        {
            context.Error += OnApplicationError;
        }

        public void Dispose()
        {
        }

        private static void OnApplicationError(object sender, EventArgs e)
        {
            try
            {
                var application = (HttpApplication)sender;
                var exception = application.Server.GetLastError();

                if (exception != null)
                {
                    lock (LockObject)
                    {
						var logger = IoC.Resolve<ILogger>();

                        if (exception.InnerException != null)
                        {
                            logger.Error(GetExceptionMessage(exception.InnerException), exception.InnerException);
                        }
                        else
                        {
                            logger.Error(GetExceptionMessage(exception), exception);
                        }
                    }
                }

                if (IsCustomErrorMode())
                {
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Server.ClearError();

                    var routeData = new RouteData();
                    routeData.Values.Add("controller", "Error");
                    routeData.Values.Add("action", "Index");
                    routeData.Values.Add("exc", exception);
					routeData.DataTokens["Namespaces"] = new[] { "VideoSeller.Controllers" };

                    var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData);

					//using (var errorController = (ErrorController)ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, "Error"))
					//{
					//    ((IController)errorController).Execute(requestContext);
					//}
                }
            }
            catch (Exception ex)
            {
                var logger = IoC.Resolve<ILogger>();
                logger.Error(ex.Message, ex);
            }
        }

        private static bool IsCustomErrorMode()
        {
            var config = WebConfigurationManager.OpenWebConfiguration("~");
            var section = (CustomErrorsSection)config.GetSection("system.web/customErrors");

            return (section.Mode == CustomErrorsMode.RemoteOnly && !HttpContext.Current.Request.IsLocal) ||
                    section.Mode == CustomErrorsMode.On;
        }

        private static string GetExceptionMessage(Exception ex)
        {
            var userName = "user is anonymous";

            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                userName = HttpContext.Current.User.Identity.Name;
            }

            return String.Format(
                "Message: {0}\nRequest URL: {1}.\nIP: {2}.\nUser login: {3}.",
                ex.Message,
                HttpContext.Current.Request.Url,
                HttpContext.Current.Request.UserHostAddress,
                userName);
        }
    }
}